package com.comleader.uap.service;

import java.util.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.comleader.client.dict.domain.qo.DictQo;
import com.comleader.client.dict.model.RemoteDictService;
import com.comleader.common.core.domain.R;
import com.comleader.uap.common.constant.Constant;
import com.comleader.uap.common.convert.ExcelDictConvert;
import com.comleader.uap.pojo.dto.DictDataDTO;

import cn.hutool.http.HttpStatus;
import lombok.extern.slf4j.Slf4j;

/**
 * @Dscription
 * @Author 连新景
 * @Date 2024/11/27 10:28
 */
@Slf4j
@Service
public class DictService {

    @Resource
    private RemoteDictService remoteDictService;

    @PostConstruct
    public void init() {
        ExcelDictConvert.dictMap = listAllDict();
    }

    /**
     * @Description 根据字典编码获取字典数据
     * @Auhtor 连新景
     * @Date 2024/12/11 17:41
     * @param dictCode
     * @return java.util.List<com.comleader.uap.pojo.dto.DictDTO.DictData>
     */
    public List<DictDataDTO> listDictDataByCode(String dictCode) {
        List<DictDataDTO> list = new ArrayList<>();
        DictQo dictQo = DictQo.builder().setDictCode(dictCode).build();
        R<List<Map<String, Object>>> reult = remoteDictService.getDictByCode(dictQo);
        if (reult != null && reult.getCode() == HttpStatus.HTTP_OK) {
            List<Map<String, Object>> dictDataList = reult.getData();
            dictDataList.forEach(data -> {
                DictDataDTO dictData = new DictDataDTO();
                dictData.setName((String)data.get("name"));
                dictData.setValue((String)data.get("value"));
                list.add(dictData);
            });
        }
        return list;
    }

    /**
     * @Description 获取系统所有字典
     * @Auhtor 连新景
     * @Date 2024/12/11 17:40
     * @return java.util.List<com.comleader.uap.pojo.dto.DictDTO>
     */
    public Map<String, List<DictDataDTO>> listAllDict() {
        Map<String, List<DictDataDTO>> map = new HashMap<>();
        // List<DictDTO> list = new ArrayList<>();
        DictQo dictQo = DictQo.builder().setId(Arrays.asList(Constant.SYSTEM_ID)).build();
        R<Map<String, Object>> result = remoteDictService.getDictByLabel(dictQo);
        if (result != null && result.getCode() == HttpStatus.HTTP_OK) {
            Map<String, Object> mapData = result.getData();
            mapData.forEach((key, value) -> {
                List<DictDataDTO> dictDataList = new ArrayList<>();
                List<Map<String, String>> valueList = (List<Map<String, String>>)value;
                valueList.forEach(data -> {
                    DictDataDTO dictData = new DictDataDTO();
                    dictData.setName(data.get("name"));
                    dictData.setValue(data.get("value"));
                    dictDataList.add(dictData);
                });
                map.put(key, dictDataList);
            });
        }
        return map;
    }
}
